﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ConsoleLogger.cs" company="Data Ductus Malmö">
//   (c) 2010 - 2012 Data Ductus Malmö AB
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace DataDuctus.Snmp.Persistor.Core.Agent.Internal
{
  using System;
  using System.Collections.Generic;
  using System.Globalization;
  using System.Text;

  using Lextm.SharpSnmpLib;
  using Lextm.SharpSnmpLib.Pipeline;

  /// <summary>
  /// The console logger.
  /// </summary>
  internal class ConsoleLogger : ILogger
  {
    #region Constants

    /// <summary>
    /// The empty.
    /// </summary>
    private const string Empty = "-";

    #endregion

    #region Public Methods and Operators

    /// <summary>
    /// The log.
    /// </summary>
    /// <param name="context">
    /// The context.
    /// </param>
    public void Log(ISnmpContext context)
    {
      Console.WriteLine(GetLogEntry(context));
    }

    #endregion

    #region Methods

    /// <summary>
    /// The get log entry.
    /// </summary>
    /// <param name="context">
    /// The context.
    /// </param>
    /// <returns>
    /// The System.String.
    /// </returns>
    private static string GetLogEntry(ISnmpContext context)
    {
      return string.Format(
        CultureInfo.InvariantCulture, 
        "{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}", 
        DateTime.UtcNow, 
        context.Binding.Endpoint.Address, 
        context.Request.Scope.Pdu.TypeCode == SnmpType.Unknown ? Empty : context.Request.Scope.Pdu.TypeCode.ToString(), 
        GetStem(context.Request.Scope.Pdu.Variables), 
        context.Binding.Endpoint.Port, 
        context.Request.Parameters.UserName, 
        context.Sender.Address, 
        (context.Response == null) ? Empty : context.Response.Scope.Pdu.ErrorStatus.ToErrorCode().ToString(), 
        context.Request.Version, 
        DateTime.Now.Subtract(context.CreatedTime).TotalMilliseconds);
    }

    /// <summary>
    /// The get stem.
    /// </summary>
    /// <param name="variables">
    /// The variables.
    /// </param>
    /// <returns>
    /// The System.String.
    /// </returns>
    private static string GetStem(ICollection<Variable> variables)
    {
      if (variables.Count == 0)
      {
        return Empty;
      }

      var result = new StringBuilder();
      foreach (Variable v in variables)
      {
        result.AppendFormat("{0};", v.Id);
      }

      if (result.Length > 0)
      {
        result.Length--;
      }

      return result.ToString();
    }

    #endregion
  }
}